package com.wangshouyu.plugins.validator;

import org.springframework.util.ReflectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * @author 王守钰
 * @date 2021年09月06日 17:21:43
 * @description 枚举值验证处理
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

	private Class<?> enumClass;

	private String enumKey;

	private boolean blank;

	private static final String EMPTY_STR = "";
 
	@Override
	public void initialize(EnumValue constraintAnnotation) {
		blank = constraintAnnotation.blank();
		enumKey = constraintAnnotation.enumKey();
		enumClass = constraintAnnotation.enumClass();
	}
 
	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context ) {
		if(blank){
			if(null == value){
				return true;
			}
			if(value instanceof String){
				if(EMPTY_STR.equals(value)){
					return true;
				}
			}
		}
		if(null == value && blank){
			return true;
		}
		Object[] enumConstants = enumClass.getEnumConstants();
		boolean useEnumKey = true;
		// 判断枚举key是否为空
		if(null == enumKey || EMPTY_STR.equals(enumKey.trim())){
			useEnumKey = false;
		}
		boolean finalUseEnumKey = useEnumKey;
		Optional<Object> enumValueOptional = Arrays.stream(enumConstants)
				.filter(Objects::nonNull)
				.map(item -> {
					Class<?> currentClass = item.getClass();
					if(finalUseEnumKey){
						Field indexField = ReflectionUtils.findField(currentClass, enumKey);
						ReflectionUtils.makeAccessible(indexField);
						return ReflectionUtils.getField(indexField, item);
					}else{
						return currentClass.getName();
					}
				}).filter(v->v.equals(value)).findFirst();
		return enumValueOptional.isPresent();
	}
 
 
 
}